define(['moment', 'JDA' ,'module/moduleMobile/program/home/InspectSkill.service'], function (moment, JDA) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', '$timeout', 'config','$InspectSkillService',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, $timeout, config, $InspectSkillService) {
            $scope.pieChart_config = {
                innerRadiusRate:0.7,
                isShowLabel:false,
                radius:50
            };
            $scope.pie_data_work_time = [{color:'rgb(255, 204, 51)', value:0},{color:'rgb(239, 239, 239)', value:100}];
            $scope.pie_data_qty = [{color:'rgb(255, 204, 51)', value:0},{color:'rgb(239, 239, 239)', value:100}];
            $scope.employeeWorkReason = config.cache.sys_parameter.EmployeeWorkReason;
            $scope.GroupreportworkOption = (config.cache.sys_parameter['UCBModule'] == '1');
            // 20230303 modify by Alan for#: module_setting卡控
            $scope.EQP_CHK = config.cache.module_setting.EQP_CHK;
            $scope.EQP_MNG = config.cache.module_setting.EQP_MNG;
            $scope.init = function(){
                init();
                getPermission();
                if(config.setting.scanBarcod=="Y"){
                    document.getElementById('input_plot').focus();
                }
            };

            // 判斷按鈕權限
            function getPermission() {
                $scope.permission = {
                    B0202: true, // 上工
                    B0203: true, // 下工
                    B0221: true, // 上下模
                    B0211: true, // 設備稼動
                    B0210: true  // 設備點檢
                };

                if(config.cache.permissions && config.cache.permissions.length > 0){
                    for(permission in $scope.permission){
                        if(config.cache.permissions.indexOf(permission) === -1){
                            $scope.permission[permission] = false;
                        }
                    }
                }  
            }

            $scope.back = function(){
                $rootScope.changeProgram('menu', {}, true);
            };

            $scope.input_plot_blur = function () {
                // 20231110 modify by Alan for M#0149487 : 打開側邊選單時，不要focus到input_plot
                if (config.setting.scanBarcod == "Y" && !$rootScope.isShowSideSubMenu) {
                    document.getElementById('input_plot').focus();
                }
            };

            $rootScope.$watch('isShowSideSubMenu', (newVal, oldVal) => {
                // SideSubMenu關閉時，input_plot要focus
                if (oldVal === true && newVal === false) {
                    $scope.input_plot_blur();
                }
            })

            $scope.setting = function(){
                $rootScope.changeProgram('setting',{parent:'home'});
            };

            $scope.changeMachine = function(){
                $rootScope.changeProgram('mobile00',{data:{parent:'home', select_machines:$scope.machines}});
                // $rootScope.changeProgram('mobile03',{data:{parent:'home', type: '2', machines_length:$scope.machines.length}});
            };

            $scope.onMachineUser = function(machine){
                if(machine.employee_work_detail.length > 0){
                    var temp = $filter('filter')(machine.employee_work_detail, {employee_no:config.cache.account});
                    if(temp && temp.length > 0){
                        machine.employee_status = 'D';
                    } else {
                        machine.employee_status = 'U';
                    }
                    return machine.employee_status == 'D';
                } else {
                     machine.employee_status = 'U';
                    return false;
                }
            };

            $scope.QRCodeScanner = function(){
                $scope.$root.OpenScanner({
                    after : function(result){
                        $scope.barcode_plot_no = result.text;
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation : 'portrait'
                });
            };
            //上下工
            $scope.workSet = function(event, machine){
                event.stopPropagation();
                var work_mode = machine.employee_status;
                var content = {
                    work_mode : work_mode,
                    employeewrokset : [{
                        machine_no : machine.machine_no,
                        machine_name : machine.machine_name,
                        employee_no : config.cache.account,
                        work_mode : work_mode,
                        work_datetime : new Date(),
                        reason_no: ''
                    }]
                };
                beforeEmpWorkSet(content, function(){
                    employee_wrok_set_Imp(content);
                });
            };

            $scope.load_mobile01 = function(machine){
                $rootScope.changeProgram('mobile01',{data:{
                    machine_no:machine.machine_no,
                    machines_length:$scope.machines.length,
                    employee_status:machine.employee_status
                }});
            };

            $scope.load_mobile02 = function(event, machine , mode){
                event.stopPropagation();
                $rootScope.changeProgram('mobile02',{data:{
                    machine_no:machine.machine_no,
                    machine_status:machine.machine_status,
                    machines_length:$scope.machines.length,
                    mode:mode
                }});
            };
             // 20231116 modify by shiwl 0147604: 手机版上下模未上模清单显示错误
            $scope.load_mobile10 = function(event, machine){
                event.stopPropagation();
                $rootScope.changeProgram('mobile10',{data:{machine:machine, parent:'home',machine_no:machine.machine_no}});
            };

            //打开报工群组界面
            $scope.load_mobile13 = function (event, machine,machines) {
                event.stopPropagation();
                //$mdDialog.serviceDialog('mobile13Service', machine, function () {
                //    dog.bark();
                //});
                var OnWorkInfo_detail = [];
                OnWorkInfo_detail.push(machine);
                $rootScope.changeProgram('mobile13', { data: { machine: machine, machines: OnWorkInfo_detail, parent: 'home' } });
            };

            function caculatePieChart(work_time, qty){
                $scope.pie_data_work_time[0].value = work_time;
                $scope.pie_data_work_time[1].value = 100 - work_time;

                $scope.pie_data_qty[0].value = qty;
                $scope.pie_data_qty[1].value = 100 - qty;
            }

             // 是否需要人員上/下工原因，1. 上工 2. 下工 3. 皆需要
            function isNeedWorkReason(work_mode){
                var result = false;

                if($scope.employeeWorkReason){
                    if(work_mode == 'U' && $scope.employeeWorkReason == '1') {
                        result = true;
                    } else if (work_mode == 'D' && $scope.employeeWorkReason == '2') {
                        result = true;
                    } else if($scope.employeeWorkReason == '3'){
                        result = true;
                    }
                }

                return result;
            }

            function beforeEmpWorkSet(content, callback){
                if(isNeedWorkReason(content.work_mode)){
                    loadEmpWorkReason(content.work_mode, function(selectItem){
                        content.employeewrokset.forEach(function(item){
                            item.reason_no = selectItem.page_no;
                        });
                        if (callback)
                            callback();
                    });
                } else {
                    if (callback)
                        callback();
                }
            }

            // 人員原因基本資料取得
            function loadEmpWorkReason(work_mode, callback){
                var title = '';
                var query_condition_info = [{column_name:'ISSUESTATE', query_mode:'0', value:'2', merge_condition_model:'AND'}];

                if(work_mode == 'D'){ // 下工
                    title = $filter('translate')('home.plz_select_offline_reason');
                    query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'1', merge_condition_model:'AND' });
                } else if(work_mode == 'U'){ //上工
                    title = $filter('translate')('home.plz_select_online_reason');
                    query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'0', merge_condition_model:'AND' });
                }

                $MMWService.pageNumberInfoGet({
                    page_mode : '35',
                    query_condition_info: query_condition_info
                }, function(items){
                    if(items && items.length > 0){
                        $scope.$root.showSelect({
                            label : function(item){
                                return item.page_name + '(' + item.page_no + ')';
                            },
                            title: title,
                            code : 'page_no',
                            selectCode : '',
                            list : items,
                            confirm : function(selectItem, radio_dialog){
                                radio_dialog.hide();
                                if (callback)
                                    callback(selectItem);
                            }
                        });
                    } else {
                        if(work_mode == 'D'){ // 下工
                            $scope.$root.showAlert($filter('translate')('home.msg.offline_reason_empty'));
                        } else if(work_mode == 'U'){ //上工
                            $scope.$root.showAlert($filter('translate')('home.msg.online_reason_empty'));
                        }
                    }
                });
            }

            function init(){
                getUserInfo(config.cache.account, function(data){
                    $scope.user_name = config.cache.name = data.employee_name;
                    $scope.machines = [];
                    if(data.shift != 'N\\A'){
                        $scope.shift_info = config.cache.shift_info = $filter('translate')('home.shift_info', {
                            shift:data.shift,
                            start_time:moment(data.shift_start_date).format('HH:mm'),
                            end_time:moment(data.shift_end_date).format('HH:mm'),
                        });
                    } else {
                        $scope.shift_info = config.cache.shift_info = $filter('translate')('home.shift_info', {
                            shift:data.shift,
                            start_time:'00:00',
                            end_time:'00:00',
                        });
                    }
                    $scope.onwork_time = config.cache.onwork_time = '08:15';
                    FavouriteMachineInfoGet(config.cache.account, function(){});
                });
            }

             // 人員技能檢驗
             function inspectUserSkill(inspectInfo, feedback){
                if(inspectInfo.employeewrokset && inspectInfo.employeewrokset.length > 0){
                    var machineInfo = inspectInfo.employeewrokset.shift();
                    if(machineInfo.work_mode == 'U'){
                        $InspectSkillService.init({
                            parent: inspectInfo.parent,
                            machine_no: machineInfo.machine_no,
                            machine_name: machineInfo.machine_name,
                            position_no: machineInfo.position,
                            op_no: inspectInfo.op_no,
                            area_no: inspectInfo.area_no,
                            user_no: inspectInfo.user_no,
                            user_name: inspectInfo.user_name,
                            user_title: inspectInfo.user_title,
                            releaser_verified: inspectInfo.releaser_verified,
                            feedback: function(dialog){
                                if(dialog){
                                    inspectInfo.releaser_verified = dialog.releaser_verified;
                                    dialog.hide();
                                }
                                inspectUserSkill(inspectInfo, feedback);
                            }
                        });
                    }else{
                        if(feedback)
                            feedback();
                    }
                }else{
                    if(feedback)
                        feedback();
                }
            }

            function employee_wrok_set_Imp(content){
                var inspectInfo = {
                    parent: 'mobile_home',
                    op_no: '',
                    area_no: '',
                    user_no: config.cache.account,
                    user_name: config.cache.name,
                    user_title: config.cache.user_title,
                    releaser_verified: false,
                    employeewrokset : angular.extend([], content.employeewrokset)
                };
                inspectUserSkill(inspectInfo, function(){
                    employee_wrok_set(content);
                });
            }

            function logout(callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.clear_login_info_json',
                    content : {},
                    msg : 'home.msg.logouting',
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            }

            $MMWService.needLogout = function(callback){
                //20181213 add by Dustdusk for M#53378: 當自動登出時要關閉所有開窗
                $mdDialog.closeAll(function(){
                    $rootScope.showAlert($filter('translate')('error.sessionTimeout'));
                    $rootScope.changeProgram("login", true);
                    if(callback){
                        callback();
                    }
                });
            };

            function getUserInfo(userCode, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.user_information_get',
                    content : {
                        employee_no : userCode,
                        report_datetime:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                        machine_no:'A',
                        return_type : '00'
                    },
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            }

            function FavouriteMachineInfoGet(account, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_SYS.favourite_machine_info_get',
                    content : {
                        master_no:account,
                        master_type:0,
                        get_employee_data:'Y',
                        type: 'mobile'
                    },
                    success : function(data){
                        if(data.query_restult.length > 0){
                            $scope.machines = data.query_restult;
                            caculatePieChart(data.work_time_percent, data.production_number_percent);
                            callback();
                        } else {
                            $scope.$root.showConfirm($filter('translate')('home.msg.no_machine_setting') , function(dialog){
                                dialog.hide();
                                $scope.changeMachine();
                            }, function(dialog){
                                dialog.hide();
                            });
                        }
                    },
                    error : function(data){
                        $scope.$root.showAlert(data.Message , function(){
                            $scope.setting();
                        });
                    }
                });
            }

            function employee_wrok_set(content){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                    content : content,
                    success : function(data){
                        if(content.work_mode == 'U'){
                            $scope.$root.showToast($filter('translate')('home.msg.work_set_U'));
                        } else if(content.work_mode == 'D'){
                            $scope.$root.showToast($filter('translate')('home.msg.work_set_D'));
                        }
                        FavouriteMachineInfoGet(config.cache.account, function(){});
                    }
                });
            }
        }
    ];
});
